<template>
  <div>
    <el-tree
      :data="data"
      node-key="id"
      ref="selectTree"
      :expand-on-click-node="false"
      :highlight-current="true"
      :default-expand-all="true"
      :current-node-key="highlightedNodeId"
      @node-click="handleClick"
    >
      <div class="custom_tree_node" slot-scope="{ data }">
        <div :style="{ width: `calc(280px - 70px - ${(data.level-1)*16}px` }" class="label">{{ data.name }}</div>
        <div v-if="data.type=='school'" class="flex_center">
          <i @click.stop="addBranch" class="el-icon-plus"></i>
          <i @click.stop="editSchool(data.schoolId)" class="el-icon-edit"></i>
          <!--    占位符      -->
          <div style="width: 16px"></div>
        </div>
        <div v-if="data.type=='branch'" class="flex_center">
          <i @click.stop="addMajor(data.branchId,data.branchName)" class="el-icon-plus"></i>
          <i @click.stop="editBranch(data.branchId)" class="el-icon-edit"></i>
          <i @click.stop="delBranch(data.branchId)" v-if="$store.getters.curRole!='branchAdmin'" class="el-icon-delete"></i>
        </div>
        <div v-if="data.type=='major'" class="flex_center">
          <i @click.stop="addClass(data)" class="el-icon-plus"></i>
          <i @click.stop="editMajor(data)" class="el-icon-edit"></i>
          <i @click.stop="delMajor(data)" class="el-icon-delete"></i>
        </div>
        <div v-if="data.type=='class'" class="flex_center">
          <i @click.stop="editClass(data)" class="el-icon-edit"></i>
          <i @click.stop="delClass(data)" class="el-icon-delete"></i>
        </div>
      </div>
    </el-tree>

    <!-- 添加或修改分院对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      :visible.sync="branchOpen"
      width="700px"
      append-to-body
    >
      <el-form @submit.native.prevent ref="branchForm" :model="branchForm" :rules="branchFormRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="分院名称" prop="branchName">
              <el-input
                show-word-limit
                maxlength="20"
                style="width: 80%"
                v-model="branchForm.branchName"
                placeholder="请输入分院名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分院类型" prop="branchType">
              <el-select style="width: 80%" placeholder="请选择分院类型" clearable v-model="branchForm.branchType">
                <el-option v-for="(item,index) of dict.type.branch_type" :key="index" :label="item.label"
                           :value="item.value"
                >
                  {{ item.label }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系人" prop="principal">
              <el-input
                maxlength="10"
                style="width: 80%"
                v-model="branchForm.principal"
                placeholder="请输入联系人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号码" prop="tel">
              <el-input
                style="width: 80%"
                v-model="branchForm.tel"
                placeholder="请输入手机号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input
                maxlength="20"
                style="width: 80%"
                v-model="branchForm.address"
                placeholder="请输入地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面" prop="branchPic">
              <div>
                <!-- 上传图片 -->
                <div
                  v-if="branchForm.branchPic"
                  class="upload-head"
                  @click="vuecutshow=true"
                >
                  <img v-bind:src="branchForm.branchPic" class="cover"/>
                </div>
                <div v-else class="upload-head" @click="vuecutshow=true">
                  <div>
                    <img src="@/assets/images/add.png" class="add" alt="加载失败"/>
                  </div>
                  <div>上传图片</div>
                </div>

                <div class="text_tip">
                  建议图片比例16:10，支持jpg、png格式，图片小于5M
                </div>
              </div>

              <vuecut
                :w="320"
                :h="200"
                :url="branchForm.branchPic"
                @coverResult="coverResult"
                title="图片上传"
                :open.sync="vuecutshow"
              ></vuecut>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="分院简介" prop="content">
              <el-input
                style="width: 80%"
                maxlength="500"
                show-word-limit
                :autosize="{ minRows: 5, maxRows: 8 }"
                v-model="branchForm.content"
                type="textarea"
                :placeholder="`请输入分院简介`"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="branchOpen = false">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitBranchForm"
        >确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改专业对话框 -->
    <majorDialog ref="major_ref" @refreshTreeData="refreshTreeData"></majorDialog>
    <!-- 添加或修改班级对话框 -->
    <classDialog ref="class_ref" @refreshTreeData="refreshTreeData"></classDialog>
    <!-- 添加或修改班级对话框 -->
    <editSchoolDialog ref="school_ref" @refreshTreeData="refreshTreeData"></editSchoolDialog>
  </div>
</template>

<script>
import { checkPhonenot } from '@/utils/validate'
import {
  getPost_branch,
  addPost_branch,
  delPost_branch,
  updatePost_branch
} from '@/api/schoolOrganization/organization'
import majorDialog from '../major'
import classDialog from '../class'
import editSchoolDialog from './editSchoolDialog'

export default {
  name: 'organizationTrees',
  components: {
    majorDialog,
    classDialog,
    editSchoolDialog
  },
  dicts: ['branch_type'],
  data() {
    return {
      vuecutshow: false,
      branchOpen: false,
      title: '',
      highlightedNodeId: 679,
      selectId: '',
      // 表单参数
      branchForm: {
        schoolId: undefined,
        branchId: undefined,
        branchName: undefined,
        branchType: '1',
        branchPic: undefined,
        address: undefined,
        content: undefined,
        principal: undefined,
        tel: undefined
      },
      // 表单校验
      branchFormRules: {
        branchName: [
          { required: true, message: `分院名称不能为空`, trigger: 'blur' }
        ],
        branchType: [
          { required: true, message: `请选择分院类型`, trigger: 'change' }
        ],
        tel: [{ required: false, validator: checkPhonenot, trigger: 'blur' }]
      }
    }
  },
  props: {
    data: {
      type: Array,
      default: []
    },
    type: {
      type: String,
      default: ''
    },
    refreshId: {
      type: String,
      default: ''
    },
    refreshItem: {}
  },
  watch: {
    data(val, oldVal) {
      if (this.refreshId) {
        this.highlightedNodeId = this.refreshId
        this.$nextTick(() => {
          this.$refs.selectTree.setCurrentKey(this.refreshId)
        })
        this.$emit('continueRefresh', this.refreshItem)
        return
      }
      if (oldVal.length == 0) {
        this.$nextTick(() => {
          this.highlightedNodeId = val[0].id
          this.$refs.selectTree.setCurrentKey(val[0].id)
          this.$emit('handleClick', val[0])
        })
      } else {
        if (this.highlightedNodeId) {
          this.$nextTick(() => {
            this.$refs.selectTree.setCurrentKey(this.highlightedNodeId)
          })
        }
      }
    }
  },
  created() {

  },
  mounted() {

  },
  methods: {
    editSchool(schoolId) {
      this.$refs.school_ref.updateHandle(schoolId)
    },
    refreshTreeData(e) {
      this.$emit('updateTreeData', e)
    },
    submitBranchForm() {
      this.$refs['branchForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理…',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0.6)'
          })
          if (this.branchForm.branchId) {
            updatePost_branch(this.branchForm)
              .then(() => {
                this.$modal.msgSuccess('修改成功')
                this.branchOpen = false
                loading.close()
                let obj = {
                  txt: 'edit',
                  type: 'branch',
                  branchId: this.branchForm.branchId
                }
                this.$emit('updateTreeData', obj)
              })
              .catch(() => {
                loading.close()
              })
          } else {
            addPost_branch(this.branchForm)
              .then(() => {
                this.$modal.msgSuccess('新增成功')
                this.branchOpen = false
                let obj = {
                  txt: 'add',
                  type: 'branch'
                }
                this.$emit('updateTreeData', obj)
                loading.close()
              })
              .catch(() => {
                loading.close()
              })
          }
        }
      })
    },
    addBranch() {
      this.reset()
      this.title = '添加分院'
      this.branchForm.schoolId = this.$store.getters.schoolId
      this.branchOpen = true
    },
    addMajor(branchId, branchName) {
      this.$refs.major_ref.handleAdd(branchId, branchName)
    },
    editBranch(branchId) {
      this.reset()
      getPost_branch(branchId).then((res) => {
        this.branchForm = res.data
        this.branchForm.branchType = res.data.branchType + ''
        this.branchOpen = true
        this.title = `修改分院`
      })
    },
    delBranch(branchId) {
      this.$confirm('是否确认删除？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        let res = await delPost_branch(branchId)
        if (res.code == 200) {
          this.$modal.msgSuccess('删除成功')
          let obj = {
            txt: 'del',
            type: 'branch',
            branchId: branchId
          }
          this.$emit('updateTreeData', obj)
        }
      }).catch(() => {
        this.$modal.msgInfo('已取消')
      })
    },
    editMajor(data) {
      this.$refs.major_ref.handleUpdate(data.majorId, data.branchId, data.branchName)
    },
    delMajor(data) {
      this.$refs.major_ref.handleDelete(data.majorId)
    },
    addClass(data) {
      this.$refs.class_ref.handleAdd(data)
    },
    editClass(data) {
      this.$refs.class_ref.handleUpdate(data)
    },
    delClass(data) {
      this.$refs.class_ref.handleDelete(data.classId)
    },
    /** 组件返回图片 */
    coverResult(e) {
      this.branchForm.branchPic = e
    },
    handleClick(data) {
      this.highlightedNodeId = data.id
      this.$emit('handleClick', data)
    },
    expandAll() {
      this.$nextTick(() => {
        this.expandAllNodes(this.$refs.selectTree.store.root)
      })
    },
    collapseAll() {
      this.$nextTick(() => {
        this.collapseAllNodes(this.$refs.selectTree.store.root)
      })
    },
    expandAllNodes(node) {
      if (node) {
        node.expanded = true
        if (node.childNodes) {
          node.childNodes.forEach(childNode => {
            this.expandAllNodes(childNode)
          })
        }
      }
    },
    collapseAllNodes(node) {
      if (node) {
        node.expanded = false
        if (node.childNodes) {
          node.childNodes.forEach(childNode => {
            this.collapseAllNodes(childNode)
          })
        }
      }
    },
    // 表单重置
    reset() {
      this.branchForm = {
        schoolId: undefined,
        branchId: undefined,
        branchName: undefined,
        branchType: '1',
        branchPic: undefined,
        address: undefined,
        content: undefined,
        principal: undefined,
        tel: undefined
      }
      this.resetForm('branchForm')
    }
  }
}
</script>

<style scoped lang="scss">
.custom_tree_node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px 0 0;
  box-sizing: border-box;

  .flex_center {
    display: flex;
    align-items: center;

    .el-icon-plus {
      font-size: 16px;
    }

    .el-icon-edit {
      margin: 0 6px;
      font-size: 16px;
    }

    .el-icon-delete {
      font-size: 16px;
      color: #fb4d27;
    }
  }

  .label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

}

::v-deep .el-tree-node__content {
  height: 40px;
}

.upload-head {
  cursor: pointer;
  position: relative;
  display: inline-block;
  width: 172px;
  height: 112px;
  border-radius: 4px;
  border: 1px dashed rgba(184, 196, 209, 1);

  .add {
    width: 29px;
    height: 29px;
    margin: 25px auto 0 auto;
  }

  div {
    font-size: 14px;
    font-weight: 400;
    color: rgba(153, 153, 153, 1);
    margin-top: 0;
    width: 100%;
    text-align: center;
  }

  .cover {
    width: 170px;
    height: 110px;
    border-radius: 4px;
  }
}

.text_tip {
  font-size: 12px;
  font-weight: 400;
  color: #a6a6a6;
}
</style>
